package com.example.controller;

import com.example.util.MsgProcessUtil;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/dy")
public class DyLiveMsgController {

    private String dyLiveUrl = "https://live.douyin.com/";

    boolean start = false;

    @RequestMapping("/startLive")
    public String startLive(String id, Model model){
        if(!start){
            start = true;
            Thread thread = new Thread(()->{
                try (Playwright playwright = Playwright.create()) {
                    Browser browser = playwright.chromium().launch();
                    Page page = browser.newPage();
                    page.onResponse(response-> {
                        MsgProcessUtil.process(response,id);
                    });
                    page.navigate(dyLiveUrl+id);
                    page.waitForClose(new Page.WaitForCloseOptions().setTimeout(0),()->{
                        System.out.println("直播间关闭");
                    });
                }
            });
            thread.setDaemon(true);
            thread.start();
        }
        model.addAttribute("id",id);
        return "index1";
    }
}
